import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { Observable } from 'rxjs';
import { PUBLIC_KEY } from '../contants/decorator.contants';
import { ApiException } from '../exceptions/api.exceptions';

@Injectable()
export default class JwtAuthGuard extends AuthGuard('jwt') {
    constructor(private reflector:Reflector) {
        super();
    }

    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        const noInterception = this.reflector.getAllAndOverride<boolean>(PUBLIC_KEY, [context.getHandler(), context.getClass()]);
        if (noInterception) return noInterception;
        return super.canActivate(context);
    }

    handleRequest<TUser = any>(err: any, user: any, info: any, context: ExecutionContext, status?: any): TUser {
        if (err || !user) {
            throw err || new ApiException("登录状态已经失效", 401)
        }
        return user;
    }
}